package com.casstime.ec.cloud.discount.services;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import com.casstime.commons.utils.IncrementIdCreator;
import com.casstime.ec.cloud.discount.dao.gift.GiftProductAuditMapper;
import com.casstime.ec.cloud.discount.dao.gift.GiftProductImageMapper;
import com.casstime.ec.cloud.discount.dao.gift.GiftProductMapper;
import com.casstime.ec.cloud.discount.dao.gift.GiftProductUpdateRecordMapper;
import com.casstime.ec.cloud.discount.dao.giftPromotion.GiftPromotionGiftMapper;
import com.casstime.ec.cloud.user.spi.models.User;
import com.casstime.ec.cloud.values.giftPromotion.GiftProduct;
import com.casstime.ec.cloud.values.giftPromotion.GiftProductAudit;
import com.casstime.ec.cloud.values.giftPromotion.GiftProductImage;
import com.casstime.ec.cloud.values.giftPromotion.GiftProductUpdateRecord;
import com.casstime.ec.cloud.values.giftPromotion.GiftPromotionGift;
import com.casstime.ec.cloud.values.giftPromotion.GiftRequest;
import com.casstime.ec.cloud.values.giftPromotion.enums.GiftProductValueEnum;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;

/**
 * ClassName: DiscountServiceImpl 
 * Function: (赠品数据实现类)
 * Reason: ADD REASON(可选).
 *  
 * @author wu.chen 
 * 2018年2月26日 上午11:02:13
 * @version   
 * @since JDK 1.8
 */
@Service
public class GiftProductDAOService {
	
	@SuppressWarnings("unused")
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private GiftProductMapper giftProductMapper;
	
	@Autowired
	private GiftProductImageMapper giftProductImageMapper;
	
	@Autowired
	private GiftProductUpdateRecordMapper updateRecordMapper;
	
	@Autowired
	private GiftProductAuditMapper giftProductAuditMapper;
	
	@Autowired
	private GiftPromotionGiftMapper giftPromotionGiftMapper;
	
	public int addGiftProduct(GiftProduct giftProduct, User user) {
		int ret = 0;
		IncrementIdCreator idCreator = new IncrementIdCreator();
		Date now = new Date();
		giftProduct.setId(idCreator.getNextIncrementId());
		giftProduct.setLastUpdatedBy(user.getUserLoginId());
		giftProduct.setLastUpdatedStamp(now);
		giftProduct.setCreatedStamp(now);
		giftProduct.setCreatedBy(user.getUserLoginId());
		//giftProduct.setAuditStatus(GiftProductValueEnum.WAIT_AUDIT.getIndex());
		giftProduct.setOnsaleStatus(GiftProductValueEnum.ONSALE_NEW.getIndex());
		if (giftProductMapper.findGiftProductByCode(giftProduct.getProductCode(), giftProduct.getProductStoreId()) != null) {
			return 0;
		}
		ret = giftProductMapper.insertOrUpdateGiftProduct(giftProduct);
		if (CollectionUtils.isNotEmpty(giftProduct.getImages())) {
			for (GiftProductImage image : giftProduct.getImages()) {
				image.setGiftId(giftProduct.getId());
				image.setId(idCreator.getNextIncrementId());
				image.setCreatedBy(user.getUserLoginId());
				image.setCreatedStamp(now);
			}
			giftProductImageMapper.insertGiftProductImages(giftProduct.getImages());
		}
		if (ret > 0) {
			List<GiftProductUpdateRecord> records = Lists.newArrayList();
			List<GiftProductAudit> audits = Lists.newArrayList();
			GiftProductUpdateRecord record = new GiftProductUpdateRecord();
			record.setId(idCreator.getNextIncrementId());
			record.setGiftId(giftProduct.getId());
			record.setTypeId("ATTRIBUTE");
			record.setUserLoginId(user.getUserLoginId());
			record.setUserLoginName(user.getUserName());
			record.setCreatedStamp(now);
			record.setDescription("新增赠品 ：" + giftProduct.getProductName());
			records.add(record);
			updateRecordMapper.insertGiftProductRecords(records);
			GiftProductAudit giftProductAudit = new GiftProductAudit();
			giftProductAudit.setId(idCreator.getNextIncrementId());
			giftProductAudit.setGiftId(giftProduct.getId());
			giftProductAudit.setAuditStatus(GiftProductValueEnum.WAIT_AUDIT.getIndex());
			giftProductAudit.setCreatedBy(user.getUserLoginId());
			giftProductAudit.setCreatedDate(now);
			giftProductAudit.setLastUpdateBy(user.getUserLoginId());
			giftProductAudit.setLastUpdateDate(now);
			audits.add(giftProductAudit);
			giftProductAuditMapper.insertOrUpdateGiftProductAudit(audits);
		}
		return ret;
	}
	
	public int updateGiftProduct(GiftProduct giftProduct, User user) {
		int ret = 0;
		IncrementIdCreator idCreator = new IncrementIdCreator();
		Date now = new Date();
		giftProduct.setLastUpdatedStamp(now);
		giftProduct.setLastUpdatedBy(user.getUserLoginId());
		GiftProduct oldGift = giftProductMapper.findGiftProductById(giftProduct.getId());
		List<String> giftIds = Lists.newArrayList();
		giftIds.add(oldGift.getId());
		List<GiftProductImage> images = giftProductImageMapper.listGiftProductImages(giftIds);
		oldGift.setImages(images);
		ret = giftProductMapper.insertOrUpdateGiftProduct(giftProduct);
		giftProductImageMapper.deleteGiftProductImages(giftProduct.getId());
		if (CollectionUtils.isNotEmpty(giftProduct.getImages())) {
			for (GiftProductImage image : giftProduct.getImages()) {
				image.setGiftId(giftProduct.getId());
				image.setId(idCreator.getNextIncrementId());
			}
			giftProductImageMapper.insertGiftProductImages(giftProduct.getImages());
		}
		if (ret > 0) {
			List<GiftProductUpdateRecord> records = Lists.newArrayList();
			GiftProductUpdateRecord record = new GiftProductUpdateRecord();
			record.setId(idCreator.getNextIncrementId());
			record.setGiftId(giftProduct.getId());
			record.setTypeId("ATTRIBUTE");
			record.setUserLoginId(user.getUserLoginId());
			record.setUserLoginName(user.getUserName());
			record.setCreatedStamp(now);
			record.setDescription(createUpdateDescription(oldGift, giftProduct, user));
			records.add(record);
			if (StringUtils.isNotBlank(record.getDescription())) {
				updateRecordMapper.insertGiftProductRecords(records);
			}
		}
		
		
		return ret;
	}
	
	public Page<GiftProduct> listGiftProducts(GiftRequest giftReq, Integer pageNum, Integer pageSize) {
		Page<GiftProduct> pagedResult = PageHelper.startPage(pageNum, pageSize);
		giftProductMapper.listGiftProducts(giftReq);
		List<GiftProduct> retProducts = pagedResult.getResult();
		
		if (CollectionUtils.isNotEmpty(retProducts)) {
			List<String> giftProductIds = retProducts.stream().map(GiftProduct::getId).collect(Collectors.toList());
			List<GiftProductImage> images = giftProductImageMapper.listGiftProductImages(giftProductIds);
			if (CollectionUtils.isNotEmpty(images)) {
				for (GiftProduct gift : retProducts) {
					for (GiftProductImage image : images) {
						if (image.getGiftId().equals(gift.getId())) {
							if (gift.getImages() == null) {
								List<GiftProductImage> temps = Lists.newArrayList();
								temps.add(image);
								gift.setImages(temps);
							} else {
								gift.getImages().add(image);
							}
						}
					}
				}
			}
		}
		
		return pagedResult;
	}
	
	public int shelvesGiftProduct(List<String> giftIds, String onsaleStatus, User user) {
		return giftProductMapper.updateOnsaleStatus(giftIds, onsaleStatus);
	}
	
	public List<String> validGiftProduct(List<String> giftIds, String onsaleStatus, User user) {
		if ("ONSALE_NO".equals(onsaleStatus)) {
			List<GiftPromotionGift> listGiftPromotionGift = giftPromotionGiftMapper.listPromotionGiftsByGiftIds(giftIds);
			List<String> listGiftIds =  listGiftPromotionGift.stream().map(GiftPromotionGift::getGiftId).collect(Collectors.toList());
			if (CollectionUtils.isNotEmpty(listGiftIds)) {
				List<GiftProduct> listGiftProduct = giftProductMapper.findGiftProductByIds(listGiftIds);
				List<String> listGiftProductName = listGiftProduct.stream().map(GiftProduct::getProductName).collect(Collectors.toList());
				return listGiftProductName;
			}
		}
		return Lists.newArrayList();
	}
	
	public List<GiftProduct> findGiftProductByIds(@RequestBody List<String> giftIds) {
		List<GiftProduct> retList = giftProductMapper.findGiftProductByIds(giftIds);
		List<GiftProductImage> findImages = giftProductImageMapper.listGiftProductImages(giftIds);
		for (GiftProduct product : retList) {
			for (GiftProductImage image : findImages) {
				if (image.getGiftId().equals(product.getId())) {
					if (product.getImages() != null) {
						product.getImages().add(image);
					} else {
						List<GiftProductImage> temps = Lists.newArrayList();
						temps.add(image);
						product.setImages(temps);
					}
				}
			}
		}
		return retList;
	}
	
	private String createUpdateDescription(GiftProduct oldGift, GiftProduct newGift, User user) {
		String ret = "";
		if (oldGift.getProductCode() != null && !oldGift.getProductCode().equals(newGift.getProductCode())) {
			ret += MessageFormat.format("修改编码 由 {0} 修改成  {1}；", oldGift.getProductCode(), newGift.getProductCode());
		} 
		if (oldGift.getProductName() != null && !oldGift.getProductName().equals(newGift.getProductName())) {
			ret += MessageFormat.format("修改名称 由 {0} 修改成  {1}；", oldGift.getProductName(), newGift.getProductName());
		}
		if (oldGift.getMarketPrice() != null && !oldGift.getMarketPrice().equals(newGift.getMarketPrice())) {
			ret += MessageFormat.format("修改价值 由 {0} 修改成  {1}；", oldGift.getMarketPrice(), newGift.getMarketPrice());
		}
		List<String> oldImages = Lists.newArrayList();
		if (CollectionUtils.isNotEmpty(oldGift.getImages())) {
			for (GiftProductImage image : oldGift.getImages()) {
				oldImages.add(image.getListImageUrl().split("\\?version")[0]);
			}
		}
		List<String> newImages = Lists.newArrayList();
		if (CollectionUtils.isNotEmpty(newGift.getImages())) {
			for (GiftProductImage image : newGift.getImages()) {
				newImages.add(image.getListImageUrl().split("\\?version")[0]);
			}
		}
		boolean flag = false;
		if (oldImages.size() != newImages.size()) {
			flag = true;
		} else {
			oldImages.removeAll(newImages);
			if (oldImages.size() > 0) {
				flag = true;
			}
		}
		if (flag) {
			ret += "修改图片；";
			List<String> giftIds = Lists.newArrayList();
			giftIds.add(newGift.getId());
			List<GiftProductAudit> listGiftProductAudit = findGiftProductAuditByGiftIds(giftIds);
		    this.auditGiftProductByIds(listGiftProductAudit, GiftProductValueEnum.WAIT_AUDIT.getIndex(), 
		    		"供应商修改了图片", user);
			
		}
		return ret;
	}

	/**
	 * auditGiftProductByIds:(根据商品ID审核商品).<br/>   
	 * @param giftIds
	 * @param user
	 * @return
	 * @author 徐彪
	 * @date 2018年3月20日 上午11:14:24
	 */
	public int auditGiftProductByIds(List<GiftProductAudit> listGiftProductAudit, String auditStatus, String auditReason, User user) {
		Map<String, String> map = new HashMap<String, String>();
		List<GiftProductAudit> newListGiftProduct = new ArrayList<GiftProductAudit>();
		for (GiftProductAudit giftProductAudit : listGiftProductAudit) {
			//记录oldAuditStatus
			map.put(giftProductAudit.getId(), giftProductAudit.getAuditStatus());
			if (auditStatus.equals(GiftProductValueEnum.PASS_AUDIT.getIndex())) {
				giftProductAudit.setAuditStatus(GiftProductValueEnum.PASS_AUDIT.getIndex());
			} else if (auditStatus.equals(GiftProductValueEnum.DENY_AUDIT.getIndex())) {
				giftProductAudit.setAuditStatus(GiftProductValueEnum.DENY_AUDIT.getIndex());
			} else if (auditStatus.equals(GiftProductValueEnum.WAIT_AUDIT.getIndex())) {
				giftProductAudit.setAuditStatus(GiftProductValueEnum.WAIT_AUDIT.getIndex());
			}
			giftProductAudit.setAuditReason(auditReason);
			giftProductAudit.setLastUpdateBy(user.getUserLoginId());
			giftProductAudit.setLastUpdateDate(new Date());
			newListGiftProduct.add(giftProductAudit);
		}
		int i = giftProductAuditMapper.insertOrUpdateGiftProductAudit(newListGiftProduct);
		//储存审核记录
		createProductAuditRecord(newListGiftProduct, map, auditReason, user);
		return i;
	}
	
	/**
	 * createProductAuditRecord:(将审核记录插入gift_product_update_record表中).<br/>   
	 * @param listGiftProduct
	 * @param user
	 * @author 徐彪
	 * @date 2018年3月20日 下午2:27:35
	 */
	public void createProductAuditRecord(List<GiftProductAudit> listGiftProductAudit, Map<String, String> map, String auditReason, User user) {
		List<GiftProductUpdateRecord> listUpdateRecord = new ArrayList<GiftProductUpdateRecord>();
		IncrementIdCreator idCreator = new IncrementIdCreator();
		for (GiftProductAudit giftProductAudit : listGiftProductAudit) {
			GiftProductUpdateRecord updateRecord = new GiftProductUpdateRecord();
			updateRecord.setId(idCreator.getNextIncrementId());
			updateRecord.setGiftId(giftProductAudit.getGiftId());
			updateRecord.setTypeId("AUDIT");
			updateRecord.setUserLoginId(user.getUserLoginId());
			updateRecord.setUserLoginName(user.getUserName());
			updateRecord.setCreatedStamp(new Date());
			String auditStatus = map.get(giftProductAudit.getId());
			if ("WAIT_AUDIT".equals(auditStatus) && giftProductAudit.getAuditStatus().equals("PASS_AUDIT")) { 
				updateRecord.setDescription(GiftProductValueEnum.WAIT_AUDIT.getName() + "，变更为 ：" + GiftProductValueEnum.PASS_AUDIT.getName());
			} else if ("WAIT_AUDIT".equals(auditStatus) && giftProductAudit.getAuditStatus().equals("DENY_AUDIT")) {
				updateRecord.setDescription(GiftProductValueEnum.WAIT_AUDIT.getName() + "，变更为 ：" + GiftProductValueEnum.DENY_AUDIT.getName()
				+ "；审核意见：" + auditReason);
			} else if ("DENY_AUDIT".equals(auditStatus) && giftProductAudit.getAuditStatus().equals("PASS_AUDIT")) {
				updateRecord.setDescription(GiftProductValueEnum.DENY_AUDIT.getName() + "，变更为 ：" + GiftProductValueEnum.PASS_AUDIT.getName());
			} else if ("PASS_AUDIT".equals(auditStatus) && giftProductAudit.getAuditStatus().equals("DENY_AUDIT")) {
				updateRecord.setDescription(GiftProductValueEnum.PASS_AUDIT.getName() + "，变更为 ：" + GiftProductValueEnum.DENY_AUDIT.getName()
				+ "；审核意见：" + auditReason);
			} else if ("DENY_AUDIT".equals(auditStatus) && giftProductAudit.getAuditStatus().equals("DENY_AUDIT")) {
				updateRecord.setDescription(GiftProductValueEnum.DENY_AUDIT.getName() + "，变更为 ：" + GiftProductValueEnum.DENY_AUDIT.getName()
				+ "；审核意见：" + auditReason);
			} else if ("PASS_AUDIT".equals(auditStatus) && giftProductAudit.getAuditStatus().equals("PASS_AUDIT")) {
				return;
			}
			listUpdateRecord.add(updateRecord);
		}
		updateRecordMapper.insertGiftProductRecords(listUpdateRecord);
	}
	
	/**
	 * findGiftProductUpdateRecordById:(根据赠品Id和类型查询赠品信息).<br/>  
	 * @param giftId
	 * @param typeId
	 * @return
	 * @author 徐彪
	 * @date 2018年3月20日 下午3:42:03
	 */
	public List<GiftProductUpdateRecord> findGiftProductUpdateRecordById(String giftId, String typeId) {
		return updateRecordMapper.listGiftProductRecords(giftId, typeId);
	}
	
	/**
	 * findGiftProductAuditByGiftIds:(根据赠品ID查找赠品处理类).<br/>  
	 * @param giftIds
	 * @return
	 * @author 徐彪
	 * @date 2018年3月23日 上午10:25:08
	 */
	public List<GiftProductAudit> findGiftProductAuditByGiftIds(List<String> giftIds) {
		return giftProductAuditMapper.findGiftProductAuditByGiftIds(giftIds);
	}
}
